from datetime import timedelta, datetime, timezone

import jwt

SECRET_KEY = "asgfddasdasdasgerher"


# 定义签名密钥，用于校验jwt的有效、合法性

def create_token(username, role):
    """基于jwt创建token的函数"""
    headers = {
        "alg": "HS256",
        "typ": "JWT"
    }
    now = datetime.now(tz=timezone.utc)
    payload = {
        "username": username,
        "exp": now + timedelta(minutes=30),
        "nbf": now,
        "iat": now,
        "iss": "lhou",
        "role": role

    }
    token = jwt.encode(payload=payload, key=get_secret_key(), algorithm='HS256', headers=headers)
    # 返回生成的token
    return token


def validate_token(token):
    """校验token的函数，校验通过则返回解码信息"""
    payload = None
    msg = None
    try:
        payload = jwt.decode(jwt=token,
                             key=get_secret_key(),
                             algorithms=['HS256'],
                             leeway=timedelta(minutes=30),
                             )
        # jwt有效、合法性校验
    except jwt.ExpiredSignatureError:
        msg = 'token已失效'
    except jwt.DecodeError:
        msg = 'token认证失败'
    except jwt.InvalidTokenError:
        e = jwt.InvalidTokenError
        msg = '非法的token'
    return payload, msg


def get_secret_key():
    return SECRET_KEY
